package com.bilubi.reggie.reggie.controller;

import com.bilubi.reggie.reggie.bean.Order;
import com.bilubi.reggie.reggie.bean.User;
import com.bilubi.reggie.reggie.bean.vo.OrderVo;
import com.bilubi.reggie.reggie.common.R;
import com.bilubi.reggie.reggie.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @RequestMapping(value = "/userPage", method = RequestMethod.GET)
    public R<PageInfo<OrderVo>> getNewOrder(@RequestParam(value = "page") Integer page, @RequestParam(value = "pageSize") Integer pageSize){
        PageHelper.startPage(page, pageSize);
        List<OrderVo> orderVos = orderService.selectAllOrderByUserId();
        PageInfo<OrderVo> pageInfo = new PageInfo<>(orderVos);
        return R.success(pageInfo);
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public R<String> submit(@RequestBody Order order, HttpSession session){
        User user = (User) session.getAttribute("user");
        order.setUserId(user.getId());
        orderService.submit(order);
        return R.success();
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public R<PageInfo<OrderVo>> getOrder(@RequestParam(value = "page") Integer page,
                                         @RequestParam(value = "pageSize") Integer pageSize,
                                         @RequestParam(value = "beginTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
                                         @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                         @RequestParam(value = "number", required = false) String number){
        log.info("beginTime:{},endTime:{}", beginTime, endTime);
        PageHelper.startPage(page, pageSize);
        List<OrderVo> orderVos = orderService.selectAllOrderByUserIdAndTime(beginTime, endTime, number);
        PageInfo<OrderVo> pageInfo = new PageInfo<>(orderVos);
        return R.success(pageInfo);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public R<String> updateStatus(@RequestBody Order order){
        orderService.updateStatus(order);
        return R.success();
    }

}
